import { NzMessageService } from 'ng-zorro-antd/message';
import { UploadService } from './../../../../../../services/upload.service';
import { Component, OnInit } from '@angular/core';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer } from 'rxjs';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { OrganizationService } from 'src/app/services/organization.service';
import { Tools } from '../../../../../../common/tools/tools';

@Component({
  selector: 'zepride-add-image-modal',
  templateUrl: './add-image-modal.component.html',
  styleUrls: ['./add-image-modal.component.less']
})
export class AddImageModalComponent implements OnInit {
  imageName: string;

  constructor(
    public uploadService: UploadService,
    public msg: NzMessageService,
    public organizationService: OrganizationService,
    private modal: NzModalRef
  ) { }

  ngOnInit(): void {
  }

  ok() {
    if (!this.imageName) {
      this.msg.error('请填写图片名称！');
      return;
    }
    let result = this.fileList.map(x => {
      return {
        uid: x.uid,
        name: this.imageName,
        url: x.url
      }
    })
    this.modal.close(result);
  }
  cancel() {
    this.modal.close();
  }

  fileList: NzUploadFile[] = [];

  loading;
  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          this.loading = false;
          if (this.fileList.length > 0) {
            this.fileList = [];
          }
          this.fileList = [{
            url: `${this.organizationService.uploadUrl}${info.file.response.fileUrl}`,
            status: 'done',
            uid: Tools.GetGuid(),
            name: 'image.png'
          }];

        });
        break;
      case 'error':
        this.loading = false;
        this.msg.error('Network error');
        break;
    }
  }

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp';
      if (!isJpgOrPng) {
        this.msg.error('只能选择图片格式的文件！');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片大小不能超过2MB！');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }
  del() {
    this.fileList = []
  }
}
